import { ModalForm, ProForm, ProFormDatePicker, ProFormSelect, ProFormText, ProFormTextArea, ProFormTimePicker } from '@ant-design/pro-components';
import type { Meeting } from '@fill/client';
import { queryClient, rspc } from '@fill/client';
import { Button, Form } from 'antd';
import dayjs from 'dayjs';
import { useState } from 'react';
import { STATUS_VALUE } from '../../constants/default';
import { UploadFile } from '../report/Upload';

export const CreateMeeting = () => {
  // const [show, setShow] = useState(false);
  const [form] = Form.useForm<Meeting>();
  const [open, setOpen] = useState(false);

  const meetingSave = rspc.useMutation('meetings.save');

  async function handleSubmit(tmp = false) {
    try {
      await form.validateFields();
    }
    catch (error) {
      return;
    }
    const values = form.getFieldsValue();
    console.log(values);
    await meetingSave.mutateAsync({
      arg: {
        uuid: values.uuid || null,
        slug: values.slug,
        started_at: dayjs(values.started_at).format('YYYY-MM-DD HH:mm:ss'),
        time: (values.time as unknown as string[]).map(item => dayjs(item).format('HH:mm')).join(),
        presenter: values.presenter,
        types: values.types,
        members: (values.members as unknown as string[]).join(),
        outline: values.outline?.replaceAll('\n', '<br />') || '',
        attachment: JSON.stringify(values.attachment || []),
        status: tmp ? STATUS_VALUE.PENDING : STATUS_VALUE.PROCESSED,
      },
    }, {
      onSuccess() {
        queryClient.refetchQueries({
          queryKey: ['meetings.get'],
        });
      },
    });

    setOpen(false);
  }

  return (
    <>
      <Button type="primary" onClick={() => setOpen(true)}>
        新增
      </Button>
      <ModalForm<Meeting>
        width={1000}
        title="新增研究整改工作"
        // trigger={
        //   <Button type="primary">
        //     新增
        //   </Button>
        // }
        open={open}
        form={form}
        layout="horizontal"
        modalProps={{
          destroyOnClose: true,
          onCancel: () => console.log('run'),
        }}
        grid
        labelCol={{ span: 4 }}
        rowProps={{
          gutter: [6, 6],
        }}
        // onFinish={async (values) => {
        //   try {
        //     await meetingSave.mutateAsync({
        //       arg: {
        //         uuid: values.uuid || null,
        //         slug: values.slug,
        //         started_at: dayjs(values.started_at).format('YYYY-MM-DD HH:mm:ss'),
        //         time: (values.time as unknown as string[]).join(),
        //         presenter: values.presenter,
        //         type: values.type,
        //         members: (values.members as unknown as string[]).join(),
        //         outline: values.outline || '',
        //         attachment: JSON.stringify(values.attachment || []),
        //         status: STATUS_VALUE.PROCESSED,
        //       },
        //     }, {
        //       onSuccess() {
        //         queryClient.refetchQueries({
        //           queryKey: ['meetings.get'],
        //         });
        //       },
        //     });

        //     return true;
        //   }
        //   catch (error) {
        //     return false;
        //   }
        // }}
        onOpenChange={(e) => {
          setOpen(e);
        }}
        submitter={{
          render() {
            return <div style={{
              display: 'flex',
              flex: 1,
              justifyContent: 'center',
            }}>
              {[
                <Button type="primary" key="tmp" onClick={() => handleSubmit(true)}>暂存</Button>,
                <Button type="primary" key="submit" onClick={() => handleSubmit()}>确定</Button>,
                <Button key="cancel" onClick={() => setOpen(false)}>取消</Button>,
              ]}
            </div>;
          },
        }}
      >
        <div style={{
          padding: 10,
        }}></div>
        <ProFormText
          name="slug"
          label="会议主题"
          placeholder="请输入会议主题"
          colProps={{
            md: 24,
          }}
          rules={[
            {
              required: true,
              message: '请输入会议主题',
            },
          ]}
        />
        <ProFormDatePicker
          name="started_at"
          label="会议日期"
          colProps={{
            md: 12,
          }}
          labelCol={{
            span: 8,
          }}
          width="md"
          rules={[
            {
              required: true,
              message: '请选择会议日期',
            },
          ]}
        />
        <ProFormTimePicker.RangePicker
          name="time"
          label="会议时间"
          dataFormat="HH:mm"
          fieldProps={{
            format: 'HH:mm',
          }}
          colProps={{
            md: 12,
          }}
          labelCol={{
            span: 6,
          }}
          width="md"
          rules={[
            {
              required: true,
              message: '请选择会议时间',
            },
          ]}
        />
        <ProFormText
          name="presenter"
          label="主持人"
          placeholder="请输入主持人"
          rules={[
            {
              required: true,
              message: '请输入主持人',
              max: 50,
            },
          ]}
          width="md"
          colProps={{
            md: 12,
          }}
          labelCol={{
            span: 8,
          }}
        />
        <ProFormSelect
          name="types"
          label="会议类型"
          rules={[
            {
              required: true,
              message: '请选择会议类型',
            },
          ]}
          valueEnum={{
            1: {
              text: '民主生活会',
            },
            2: {
              text: '党委会议',
            },
          }}
          width="md"
          colProps={{
            md: 12,
          }}
          labelCol={{
            span: 6,
          }}
        />
        <ProFormSelect label="参会人" rules={[
          {
            required: true,
            message: '请输入参会人',
            // max: 50,
          },
        ]} name="members" fieldProps={{
          mode: 'tags',
        }} placeholder={'请输入'} />
        <ProFormTextArea label="会议提纲" name="outline" />
        <ProForm.Item style={{
          width: '100%',
        }} labelCol={{
          span: 4,
        }} name="attachment" label="会议材料" extra="支持 doc、docx、pdf、xls、xlsx、jpg、png、jpeg、txt、ext文件格式，最大不超过200M">
          <UploadFile files={[]} onChange={(files) => { form.setFieldValue('attachment', files); }} />
        </ProForm.Item>

      </ModalForm>
    </>
  );
};
